var Public = Public || {};
var Business = Business || {};
Public.isIE6 = !window.XMLHttpRequest;	//ie64
var LODOP = LODOP || null;
if(undefined != LODOP){
	LODOP.SET_LICENSES("厦门智慧数网络科技有限公司","2CCC74198DEF8B1D8D08C1CF3F7E04F2","","");
}
Public.encodeURI=function(value){
	return encodeURI(encodeURI(value));
};
Public.setGrid = function(adjustH, adjustW){
	var adjustH = adjustH || 65;
	var adjustW = adjustW || 20;
	var gridW = $(window).width() - adjustW, gridH = $(window).height() - $(".grid-wrap").offset().top - adjustH;
	return {
		w : gridW,
		h : gridH
	};
};
//重设表格宽高
Public.resizeGrid = function(adjustH, adjustW){
	var grid = $("#grid");
	var gridWH = Public.setGrid(adjustH, adjustW);
	grid.jqGrid('setGridHeight', gridWH.h);
	grid.jqGrid('setGridWidth', gridWH.w);
};
//重设表格宽高
Public.resizeSpecifyGrid = function(gridId, adjustH, adjustW){
	var grid = $("#" + gridId);
	var gridWH = Public.setGrid(adjustH, adjustW);
	grid.jqGrid('setGridHeight', gridWH.h);
	grid.jqGrid('setGridWidth', gridWH.w);
};
//自定义报表宽度初始化以及自适应
Public.initCustomGrid = function(tableObj){
	$(tableObj).css("width") && $(tableObj).attr("width","auto");
	var _minWidth = $(tableObj).outerWidth();
	$(tableObj).css("min-width",_minWidth+"px");
	$(tableObj).width($(window).width() - 74);
	var _throttle = function(method,context){
		clearTimeout(method.tid);
		method.tid = setTimeout(function(){
			method.call(context);
		},100);
	};
	var _resize = function(){
		$(tableObj).width($(window).width() - 74);
	};
	$(window).resize(function() {
		_throttle(_resize);
	});
};

//过滤空字段
Public.nullFormatter = function(cellvalue, options, rowObject) {
    if(cellvalue === undefined || cellvalue === 'null' || cellvalue === 'NULL') {
        cellvalue = '';
    }

    return cellvalue;
};
Public.dateFormat = function(val, opt, row){
	if(null != val && "" != val){
		if(val.indexOf(".") > -1){
			val = val.substring(0,val.indexOf("."));
		}
	}
	return val;
};
//操作项格式化，适用于有“修改、删除”操作的表格
Public.operFmatter = function (val, opt, row) {
	var html_con = '<div class="operating" data-id="' +opt.rowId+ '">';
	html_con += '<i class="iconfont i-hand ui-icon-pencil" title="修改">&#xe60c;</i> <i class="iconfont i-hand ui-icon-trash" title="删除">&#xe60e;</i>';
	html_con += '</div>';
	return html_con;
};

//操作项格式化，适用于有“修改”操作的表格
Public.operEditFmatter = function (val, opt, row) {
	var html_con = '<div class="operating" data-id="' +opt.rowId+ '">';
	html_con += '<span class="iconfont i-hand ui-icon-pencil" title="修改">&#xe60c;</span>';
	html_con += '</div>';
	return html_con;
};
Public.operDelFmatter = function (val, opt, row) {
	var html_con = '<div class="operating" data-id="' +opt.rowId+ '">';
	html_con += '<i class="iconfont ui-icon-trash" title="删除">&#xe60e;</i>';
	html_con += '</div>';
	return html_con;
};
Public.hideConstion = function(){
	$('.ui-btn-menu').each(function(){
		var menu = $(this);
		if($('.con',menu).is(':visible')){
			menu.removeClass('ui-btn-menu-cur');
		}
	});
};

Public.billsOper = function (val, opt, row) {
	var html_con = '<div class="operating" data-id="' + opt.rowId + '"><span class="ui-icon ui-icon-plus" title="新增行"></span><span class="ui-icon ui-icon-trash" title="删除行"></span></div>';
	return html_con;
};

Public.dateCheck = function(){
	$('.ui-datepicker-input').bind('focus', function(e){
		$(this).data('original', $(this).val());
	}).bind('blur', function(e){
		var reg = /((^((1[8-9]\d{2})|([2-9]\d{3}))(-)(10|12|0?[13578])(-)(3[01]|[12][0-9]|0?[1-9])$)|(^((1[8-9]\d{2})|([2-9]\d{3}))(-)(11|0?[469])(-)(30|[12][0-9]|0?[1-9])$)|(^((1[8-9]\d{2})|([2-9]\d{3}))(-)(0?2)(-)(2[0-8]|1[0-9]|0?[1-9])$)|(^([2468][048]00)(-)(0?2)(-)(29)$)|(^([3579][26]00)(-)(0?2)(-)(29)$)|(^([1][89][0][48])(-)(0?2)(-)(29)$)|(^([2-9][0-9][0][48])(-)(0?2)(-)(29)$)|(^([1][89][2468][048])(-)(0?2)(-)(29)$)|(^([2-9][0-9][2468][048])(-)(0?2)(-)(29)$)|(^([1][89][13579][26])(-)(0?2)(-)(29)$)|(^([2-9][0-9][13579][26])(-)(0?2)(-)(29)$))/;
		var _self = $(this);
		setTimeout(function(){
			if(!reg.test(_self.val())) {
				parent.Public.tips({type:1, content : '日期格式有误！如：2013-08-08。'});
				_self.val(_self.data('original'));
			};
		}, 10);

	});
};

//根据之前的编码生成下一个编码
Public.getSuggestNum = function(prevNum){
	if (prevNum == '' || !prevNum) {
		return '';
	}
	var reg = /^([a-zA-Z0-9\-_]*[a-zA-Z\-_]+)?(\d+)$/;
	var match = prevNum.match(reg);
	if (match) {
		var prefix = match[1] || '';
		var prevNum = match[2];
		var num = parseInt(prevNum, 10) + 1;
		var delta = prevNum.toString().length - num.toString().length;
		if (delta > 0) {
			for (var i = 0; i < delta; i++) {
				num = '0' + num;
			}
		}
		return prefix + num;
	} else {
		return '';
	}
};

Public.bindBuySkip = function(obj, func){
	var args = arguments;
	$(obj).on('keydown', 'input:visible:not(:disabled)', function(e){
		if (e.keyCode == '13') {
			var inputs = $(obj).find('input:visible:not(:disabled)');
			var idx = inputs.index($(this));
			idx = idx + 1;
			if (idx >= inputs.length) {
				if (typeof func == 'function') {
					var _args = Array.prototype.slice.call(args, 2 );
					func.apply(null,_args);
				}
			} else {
				inputs.eq(idx).focus();
			}
		}
	});
};
Public.getRequest = Public.urlParam = function() {
   var param, url = location.search, theRequest = {};
   if (url.indexOf("?") != -1) {
      var str = url.substr(1);
      strs = str.split("&");
      for(var i = 0, len = strs.length; i < len; i ++) {
		 param = strs[i].split("=");
         theRequest[param[0]]=decodeURIComponent(param[1]);
      }
   }
   return theRequest;
};
Public.ajaxPost = function(url, params, callback){    
	$.ajax({  
	   type: "POST",
	   url: url,
	   data: params, 
	   dataType: "json",  
	   success: function(data, status){  
		   callback(data);  
	   },  
	   error: function(err){  
			Public.tips({type: 1, content : '操作失败了哦，服务可能已过期，请按F5刷新！'});
	   }  
	});  
};  
Public.ajaxGet = function(url, params, callback){    
	$.ajax({  
	   type: "GET",
	   url: url,
	   dataType: "json",  
	   data: params,    
	   success: function(data, status){  
		   callback(data);  
	   },   
	   error: function(err){  
			Public.tips({type: 1, content : '操作失败了哦，服务可能已过期，请按F5刷新！'});
	   }  
	});  
};
Public.tips = function(options){ return new Public.Tips(options); };
Public.Tips = function(options){
	var defaults = {
		renderTo: 'body',
		type : 0,
		autoClose : true,
		removeOthers : true,
		time : undefined,
		top : 65,
		onClose : null,
		onShow : null
	};
	this.options = $.extend({},defaults,options);
	this._init();
	
	!Public.Tips._collection ?  Public.Tips._collection = [this] : Public.Tips._collection.push(this);
	
};

Public.Tips.removeAll = function(){
	try {
		for(var i=Public.Tips._collection.length-1; i>=0; i--){
			Public.Tips._collection[i].remove();
		}
	}catch(e){}
};

Public.Tips.prototype = {
	_init : function(){
		var self = this,opts = this.options,time;
		if(opts.removeOthers){
			Public.Tips.removeAll();
		}

		this._create();

		this.closeBtn.bind('click',function(){
			self.remove();
		});

		if(opts.autoClose){
			time = opts.time || opts.type == 1 ? 5000 : 3000;
			window.setTimeout(function(){
				self.remove();
			},time);
		}

	},
	
	_create : function(){
		var opts = this.options;
		this.obj = $('<div class="ui-tips"><i></i><span class="close"></span></div>').append(opts.content);
		this.closeBtn = this.obj.find('.close');
		
		switch(opts.type){
			case 0 : 
				this.obj.addClass('ui-tips-success');
				break ;
			case 1 : 
				this.obj.addClass('ui-tips-error');
				break ;
			case 2 : 
				this.obj.addClass('ui-tips-warning');
				break ;
			default :
				this.obj.addClass('ui-tips-success');
				break ;
		}
		
		this.obj.appendTo('body').hide();
		this._setPos();
		if(opts.onShow){
				opts.onShow();
		}

	},

	_setPos : function(){
		var self = this, opts = this.options;
		if(opts.width){
			this.obj.css('width',opts.width);
		}
		var scrollTop = $(window).scrollTop();
		var top = parseInt(opts.top) + scrollTop;
		this.obj.css({
			position : Public.isIE6 ? 'absolute' : 'fixed',
			left : '50%',
			top : top,
			zIndex : '9999',
			marginLeft : -self.obj.outerWidth()/2	
		});

		window.setTimeout(function(){
			self.obj.show().css({
				marginLeft : -self.obj.outerWidth()/2
			});
		},150);

		if(Public.isIE6){
			$(window).bind('resize scroll',function(){
				var top = $(window).scrollTop() + parseInt(opts.top);
				self.obj.css('top',top);
			});
		}
	},

	remove : function(){
		var opts = this.options;
		this.obj.fadeOut(200,function(){
			$(this).remove();
			if(opts.onClose){
				opts.onClose();
			}
		});
	}
};
Public.numToCurrency = function(val, dec) {
	val = parseFloat(val);	
	dec = dec || 2;	//小数位
	if(val === 0 || isNaN(val)){
		return '';
	}
	val = val.toFixed(dec).split('.');
	var reg = /(\d{1,3})(?=(\d{3})+(?:$|\D))/g;
	return val[0].replace(reg, "$1,") + '.' + val[1];
};
Public.currencyToNum = function(val){
	var val = String(val);
	if ($.trim(val) == '') {
		return 0;
	}
	val = val.replace(/,/g, '');
	val = parseFloat(val);
	return isNaN(val) ? 0 : val;
};
Public.numerical = function(e){
	var allowed = '0123456789.-', allowedReg;
	allowed = allowed.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
	allowedReg = new RegExp('[' + allowed + ']');
	var charCode = typeof e.charCode != 'undefined' ? e.charCode : e.keyCode; 
	var keyChar = String.fromCharCode(charCode);
	if(!e.ctrlKey && charCode != 0 && ! allowedReg.test(keyChar)){
		e.preventDefault();
	};
};
Public.subLenString = function(str,len){
	if(len != undefined && len != null && len > 0){
		if(str.length > len){
			str = str.substring(0,len) + "...";
		}
	}else{
		len = 8;
		if(str.length > len){
			str = str.substring(0,len) + "...";
		}
	}
	return str;
};
Public.limitInput = function(obj, allowedReg){
    var ctrlKey = null;
    obj.css('ime-mode', 'disabled').on('keydown',function(e){
        ctrlKey = e.ctrlKey;
    }).on('keypress',function(e){
        allowedReg = typeof allowedReg == 'string' ? new RegExp(allowedReg) : allowedReg;
        var charCode = typeof e.charCode != 'undefined' ? e.charCode : e.keyCode; 
        var keyChar = $.trim(String.fromCharCode(charCode));
        if(!ctrlKey && charCode != 0 && charCode != 13 && !allowedReg.test(keyChar)){
            e.preventDefault();
        } 
    });
};
Public.formatMoney = function(value){
	if($.trim(value) == '' || isNaN(value)){
		return '';
	}
	return parseFloat(value).toFixed(2);
};
//单选框插件
$.fn.cssRadio = function(opts){
	var opts = $.extend({}, opts);
	var $_radio = $('label.radio', this), $_this = this;
	$_radio.each(function() {
		var self = $(this);
		if (self.find("input")[0].checked) {
			self.addClass("checked");
		};
	}).hover(function() {
		$(this).addClass("over");
	}, function() {
		$(this).removeClass("over");
	}).click(function(event) {
		$_radio.find("input").removeAttr("checked");
		$_radio.removeClass("checked");
		$(this).find("input").attr("checked", "checked");
		$(this).addClass("checked");
		opts.callback($(this));
	});
	return {
		getValue: function() {
			return $_radio.find("input[checked]").val();
		},
		setValue: function(index) {
			return $_radio.eq(index).click();
		}
	};
};

//复选框插件
$.fn.cssCheckbox = function(opts) {
    if (opts) {
        opts = $.extend({}, opts);
    }
	var $_chk = $(".chk", this);
	$_chk.each(function() {
		if ($(this).find("input")[0].checked) {
			$(this).addClass("checked");
		};
		if ($(this).find("input")[0].disabled) {
			$(this).addClass("dis_check");
		};
	}).hover(function() {
		$(this).addClass("over");
	}, function() {
		$(this).removeClass("over");
	}).click(function(event) {
		if ($(this).find("input")[0].disabled) {
			return;
		};
		$(this).toggleClass("checked");
		$(this).find("input")[0].checked = !$(this).find("input")[0].checked;
        if (opts) {
            opts.callback($(this));
        }
		event.preventDefault();
	});
	
	return {
		chkAll:function(){
			$_chk.addClass("checked");
			$_chk.find("input").attr("checked","checked");
		},	
		chkNot:function(){
			$_chk.removeClass("checked");
			$_chk.find("input").removeAttr("checked");
		},
		chkVal:function(){
			var val = [];
			$_chk.find("input:checked").each(function() {
            	val.push($(this).val());
        	});
			return val;
		}
	};
};

Business.alert = function(){
	var html = [
		'<div class="ui-dialog-tips">',
		'<h4 class="tit">您没有该功能的使用权限哦！</h4>',
		'<p>请联系管理员为您授权!</p>',
		'</div>'
	].join('');
	$.dialog({
		width: 240,
		title: '系统提示',
		icon: 'alert.gif',
		fixed: true,
		lock: true,
		resize: false,
		ok: true,
		content: html
	});
};
var mobileRegx = /^1[3|4|5|7|8][0-9]{9}$/ ;//手机号正则
var phoneRegx =/^((0[0-9]{2,3})-)([0-9]{7,8})(-([0-9]{3,}))?$/; //电话号码正则
/**校验手机号码或者电话**/
function checkTelORMoblie(tel) 
{ 
   return mobileRegx.test(tel) || phoneRegx.test(tel);
}
/**校验手机号码**/
function isMobilePhone(mobilePhone)
{
	return mobileRegx.test(mobilePhone);
}
/**校验电话号码**/
function isTelePhone(telePhone)
{
	return phoneRegx.test(telePhone);
}
/**校验QQ号码**/
function checkQQ(QQ){
	var qq = /^[1-9]{1}[0-9]{4,10}$/;
	return qq.test(QQ);
}
checkImportDate = function(sysdate){
	var hour = sysdate.substring(11,13);
	if(undefined != hour && "" != hour){
		if(parseInt(hour)<21 && parseInt(hour) >= 10){
			$.dialog.tips("10-21时不能导入大于300K!",2,"32X32/fail.png");
			return true;
		}else{
			return false;
		}
	}else{
		return false;
	}
};
/**去掉日期后面的.0*/
function date(val, opt, row){
	var dateS=val.substring(0,val.length-2);
	return dateS;
}
/**检查单个，多选框是否选中，并且改变对应值
 * name 多选框name值
 * checkedVal 选中值
 * noCheckedVal 没有选中值
 * */
function checkBoxValidate(name,checkedVal,noCheckedVal){ 
  if($("input[name="+name+"]").attr("checked")=='checked'){//选中
     $("#"+name).val(checkedVal);
  }else{
     $("#"+name).val(noCheckedVal);
  }
}
Public.getDefaultPage = function(){
	var win = window.self;
	do{
		if (win.SYSTEM) {
			return win;
		}
		win = win.parent;
	} while(true);
};
Public.openDialog=function(data){
	$.dialog({ 
	   	id: data.id,
	   	title: data.title,
	   	max: false,
	   	min: false,
	   	data:data.data,
	   	width:parseInt(data.width),
	   	height:parseInt(data.height),
	   	drag: false,
	   	cache:false,
	   	resize:false,
	   	lock:data.lock,
	   	content:'url:'+data.url
	});	
};
Public.openMax=function(data){
	$.dialog({ 
	   	id: data.id,
	   	title: data.title,
	   	max: false,
	   	min: false,
	   	data:data.data,
	   	drag: true,
	   	cache:false,
	   	resize:false,
	   	lock:false,
	   	content:'url:'+data.url
	}).max();	
};
Public.openImg=function(pd_code){
	var config = Public.getDefaultPage().CONFIG;
	$.dialog({ 
		id: 'product_img',
		title: '商品图片',
		max: false,
		min: false,
		width: 400,
		height: 320,
		fixed:false,
		drag: true,
		content:'url:'+config.BASEPATH+'cash/to_img_view?pd_code='+pd_code
	});
};
